<?php
/*
 * @Author 哲
 * @Date 2020-07-21 10:59:41
 * @LastEditTime 2020-11-05 11:33:43
 * @LastEditors 哲
 * @Description 用户设备信息
 * @FilePath \1_1to1\s_api\app\Services\Tools\Models\Qiniu.php
 */

namespace App\Services;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
use Qiniu\Config;
use Qiniu\Auth;
use Qiniu\Http\Client;


class Qiniuyun
{
    private $upManager;
    private $domain;
    private $auth;
    private $bucketName;
    private $bucketManager;

    /**
     * @desc 初始化
     * @return void
     *
     * qiniu-public
     */
    public function __construct($public = 'qiniu')
    {
        $config = config('open.'.$public);
        $this->domain = $config['domain'];
        $this->upManager = new UploadManager();
        $this->auth = new Auth($config['accessKey'], $config['secretKey']);
        $this->bucketName = $config['space_bucket'];

        $this->bucketManager = new BucketManager($this->auth);

    }

    /**
     * @desc  上传文件
     * @param  string $key 文件key
     * @param  string $filePath 文件路径
     * @return object
     */
    public function upFile($key,$filePath)
    {
        // 生成上传 Token
        $token = $this->auth->uploadToken($this->bucketName,$key);
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $this->upManager->putFile($token, $key, $filePath);
        return $err;
    }

    /**
     * @desc  上传文件-二进制
     * @param  string $key 文件key
     * @param  string $data 二进制流
     * @return object
     */
    public function put($key,$data)
    {
        // 生成上传 Token
        $token = $this->auth->uploadToken($this->bucketName,$key);
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $this->upManager->put($token, $key, $data);
        return $ret;
    }

    /**
     * 访问私有空间内容
     */
    public static function getFile($path)
    {
        if(!$path){
            return '';
        }
        if(strpos($path,'http') !== false){
            return $path;
        }
        $config = config('open.qiniu');
        $download_url = $config['domain'].$path;
        return $download_url;
    }

    // 删除指定资源，参考文档：https://developer.qiniu.com/kodo/api/1257/delete
    public function deleteFile($key, $bucket = '')
    {
        if($bucket == ''){
            $bucket = $this->bucketName;
        }
        $bucketManager = new BucketManager($this->auth);

        $bucketManager->delete($bucket, $key);
    }

    /**
     * copy 文件
     * @param $from_bucket
     * @param $from_key
     * @param $to_bucket
     * @param $to_key
     */
    public function copyFile($from_bucket, $from_key, $to_bucket, $to_key)
    {
        $bucketManager = new BucketManager($this->auth ,null);
        $data = $bucketManager->copy($from_bucket ,$from_key, $to_bucket, $to_key ,false);
        return $data;
    }

    public static function getQnRealUrl($url){
        if(!$url){
            return '';
        }
        $arr = explode('?', $url);
        $data = explode('.com/', $arr[0]);
        return $data[1];
    }

    /**
     * 七牛云token
     */
    public function getToken()
    {
        $token = $this->auth->uploadToken($this->bucketName);
        return $token;
    }

    /**
     * @desc  图片审核
     * @param  string $image 图片地址
     * @return string block:违规，review建议人工复核，pass正常。其他返回值为错误消息
     */
    public function imageCensor($image)
    {
        $url = 'http://ai.qiniuapi.com/v3/image/censor';
        $method = "POST";
        $host = "ai.qiniuapi.com";
        $contentType = "application/json";
        $scenes = ['pulp','terror','politician'];
        $image = $this->getFile($image);
        $body['data'] = [
            'uri' => $image,
        ];
        $body['params'] = [
            'scenes' => $scenes,
        ];
        $body = \json_encode($body);
        $headers = $this->auth->authorizationV2($url, $method, $body, $contentType);
        $headers['Content-Type'] = $contentType;
        $headers['Host'] = $host;
        $response = Client::post($url, $body, $headers);
        $ret = json_decode($response->body);
        if (isset($ret->code) && $ret->code == 200){
            $result = $ret->result;
            switch ($result->suggestion) {
                case 'pass':
                    $res['censor_status'] = 1;
                    break;
                case 'review':
                    $res['censor_status'] = 2;
                    $res['censor_result'] = $this->censorData($result->scenes);
                    break;
                case 'block':
                    $res['censor_status'] = 3;
                    $res['censor_result'] = $this->censorData($result->scenes);
                    break;
                default:
                    //扩充类型
                    $res['censor_status'] = 99;
                    break;
            }
        }else{
            $res['censor_status'] = 4;
        }
        return $res;
    }

    /**
     * @desc  图片审核详情数据格式处理
     * @param  array $data 详情数据
     */
    public function censorData($data)
    {
        $arr = array();
        $censor = config('open.qiniu')['censor'];
        foreach($data as $k=>$v){
            if($v->suggestion != 'pass'){
                $details = $v->details;
                $arr[$k]['name'] = $censor[$k]['name'];
                foreach($details as $ks=>$vs){
                    if($k == 'politician'){
                        $arr[$k]['result'][$ks] = $censor[$k]['data'][$vs->group].' : '.$vs->label;
                    }else{
                        $arr[$k]['result'][$ks] = $censor[$k]['data'][$vs->label];
                    }
                }
            }
        }
        return json_encode($arr);
    }
}
